# _*_ coding:utf-8 _*_
# @Time : 2023/5/25 17:57
# @Author : wsl
# @File : day05_demo
# @Project : python  案例 获取kfc第n页数据保存
import urllib.parse
import urllib.request


# 接口GetStoreList.ashx?op=cname    http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname
# 荷载
# cname: 上海
# pid:
# pageIndex: 1
# pageSize: 10
def create_request(page1):
    base_url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname'

    data = {
        'cname': '上海',
        'pid': '',
        'pageIndex': page1,
        'pageSize': '10'
    }
    data = urllib.parse.urlencode(data).encode('utf-8')

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/113.0'
    }

    request1 = urllib.request.Request(url=base_url, headers=headers,data=data)
    return request1


def get_content(request1):
    response = urllib.request.urlopen(request1)
    content1 = response.read().decode('utf‐8')
    return content1


def down_load(page1, content1):
    with open('../image/output/kfc/kfc_' + str(page1) + '.test.json', 'w', encoding='utf‐8')as fp:
        fp.write(content1)


if __name__ == '__main__':
    start_page = int(input('起始页码'))  # string ->int
    end_page = int(input('结束页码'))

    for page in range(start_page, end_page + 1):
        request = create_request(page)
        content = get_content(request)
        down_load(page, content)
